<template>
  <div class="hello">
  <label style="border:1px solid #000">
    <input type="file" style="display:none" @change="selectFile" ref="fileInput" multiple/>
    本地文件
  </label>
   <div class="block">
     <span>控制音量</span>
     <el-slider v-model="volume" @change="handleVolume"></el-slider>
   </div>
   <div class="block">
     <span>控制速度</span>
     <el-slider v-model="speed" @change="handleSpeed" :step="25" show-stops :format-tooltip="formatTooltip"></el-slider>
   </div>
  <ul>
    <li v-for="(item, index) in fileList" :key="index" :class="{'active': activeIndex === index}" @click="playMusic(index)">{{item}}</li>
  </ul>
  </div>
</template>

<script>
// 通过设置audio.volume、audio.playbackRate来改变音乐的播放音量大小和播放速度
export default {
  data () {
    return {
      fileList: [],
      event: null,
      activeIndex: -1,
      audio: null,
      volume: 1,
      speed: 25
    }
  },
  mounted () {
    this.initAudio()
  },
  methods: {
    selectFile (e) {
      let files = e.target.files
      for (const key in files) {
        if (files.hasOwnProperty(key)) {
          const str = files[key].name
          this.fileList.push(str)
        }
      }
      this.event = e
      setTimeout(() => {
        this.musicPlay(this.event.target.files[0])
        this.activeIndex = 0
      }, 1000)
    },
    initAudio () { // 初始化
      this.audio = new Audio()
      this.audio.addEventListener('ended', () => { // 添加音频结束事件
        this.nextMusic()
      })
    },
    nextMusic () {
      this.activeIndex++
      if (this.activeIndex > this.fileList.length - 1) {
        this.activeIndex = 0
      }
      this.musicPlay(this.event.target.files[this.activeIndex])
    },
    musicPlay (str) {
      let reader = new FileReader()
      reader.readAsDataURL(str)
      reader.onload = () => {
        this.audio.src = reader.result
        this.audio.play()
      }
    },
    playMusic (val) {
      this.activeIndex = val
      this.musicPlay(this.event.target.files[this.activeIndex])
    },
    handleVolume () {
      this.audio.volume = this.volume / 100
    },
    handleSpeed () {
      switch (this.speed) {
        case 0:
          this.audio.playbackRate = 0.5
          break
        case 25:
          this.audio.playbackRate = 1.0
          break
        case 50:
          this.audio.playbackRate = 1.5
          break
        case 75:
          this.audio.playbackRate = 2.0
          break
        case 100:
          this.audio.playbackRate = 3.0
          break
      }
    },
    formatTooltip (val) {
      switch (val) {
        case 0:
          return '0.5 半速（更慢）'
        case 25:
          return '1.0 正常速度'
        case 50:
          return '1.5 倍速（快）'
        case 75:
          return '2.0 倍速（更快）'
        case 100:
          return '3.0 倍速（非常快）'
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.active {
  color: red;
}
.block {
  width: 50%;
  margin: 0 auto;
}
</style>
